﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Bibliotheek;
using Microsoft.VisualBasic;
using Serie_Counter.Presentatie;
using Serie_Counter.BusinissLayer;
using Serie_Counter.General;

namespace Serie_Counter.Presentatie
{
    public partial class SerieControlForm : Form
    {

        BL_Manager manager;
        private int season;
        private int episode;
        private int curEpisode;
        private int curSeason;
        private int frequency;
        private DateTime nextAirDate;
        private Serie serie;
        private SelectedCollection selectedCollection;
        private reDrawScreen reDrawScreen;
        private MemoryStream coverStream;
        

        #region Add functions

        /// <summary>
        /// constructor for add usage
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="selectedCollection"></param>
        public SerieControlForm(BL_Manager manager, SelectedCollection selectedCollection = SelectedCollection.Active)
        {
            InitializeComponent();
            
            this.manager = manager;
            this.selectedCollection = selectedCollection;
            
            //add click handler
            buttonAddOrUpdate.Click += new EventHandler(buttonAdd_Click);
            buttonAddOrUpdate.Text = "Add";

            textBoxTitel.Leave += new EventHandler(FindCover);
            pictureBoxPic.SizeMode = PictureBoxSizeMode.Zoom;
            pictureBoxPic.Image = Image.FromFile(GeneralVars.DEFAULT_COVER_PATH);

            ToolTip checkboxTooltip = new ToolTip();
            checkboxTooltip.SetToolTip(checkBoxSaveCover,"When checked, the cover will be saved when adding the serie.");

            ToolTip frequencyToolTip = new ToolTip();
            frequencyToolTip.SetToolTip(textBoxFrequency,"Give a number of days");
            this.Text = "Add serie";
            
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            
            if (!CheckError())
            {
                //not saving the cover
                if(!checkBoxSaveCover.Checked)
                {
                    coverStream = null;
                }
                 
                manager.addSerie(textBoxTitel.Text, season, episode, nextAirDate,frequency,curSeason,curEpisode, coverStream, selectedCollection,textBoxDestMovePath.Text);
                this.Dispose();
            }
        }

        

        #endregion


        #region Update functions

        private bool picChange = false;

        /// <summary>
        /// constructor for update usage
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="serie"></param>
        /// <param name="reDrawScreen"></param>
        /// <param name="selectedCollection"></param>
        public SerieControlForm(BL_Manager manager, Serie serie, reDrawScreen reDrawScreen, SelectedCollection selectedCollection = SelectedCollection.Active)
        {
            InitializeComponent();
            //ini fields
            textBoxAirDate.Text = serie.NextAirDate.ToShortDateString();
            textBoxEpisode.Text = serie.Episode.ToString();
            textBoxSeason.Text = serie.Season.ToString();
            textBoxTitel.Text = serie.Titel;
            if(serie.Frequency != 0)
            {
                textBoxFrequency.Text = serie.Frequency.ToString();
            }
            textBoxCurEpisode.Text = serie.CurEpisode.ToString();
            textBoxCurSeason.Text = serie.CurSeason.ToString();
            checkBoxSaveCover.Checked = false;
            //moving path
            textBoxDestMovePath.Text = serie.TransferPath;
            
            //save vars
            this.manager = manager;
            this.serie = serie;
            this.selectedCollection = selectedCollection;
            this.reDrawScreen = reDrawScreen;

            //add click handler
            buttonAddOrUpdate.Click += new EventHandler(buttonUpdate_Click);
            buttonAddOrUpdate.Text = "Update";

            //show picture
            pictureBoxPic.SizeMode = PictureBoxSizeMode.Zoom;
            try
            {
                pictureBoxPic.Image = Image.FromFile(serie.CoverPath);
            }
            catch (Exception)
            {

                try
                {
                    pictureBoxPic.Image = Image.FromFile(GeneralVars.DEFAULT_COVER_PATH);
                }
                catch (FileNotFoundException e)
                {
                    MessageBox.Show("Default cover pic not found!" + e.Message, "Cover error", MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);
                }
            }

            //hide checkbox
            checkBoxSaveCover.Visible = false;

            //tooltip
            ToolTip pictureboxInfo = new ToolTip();
            pictureboxInfo.SetToolTip(pictureBoxPic,"Right click to check for a cover online");

            //checkbox tooltip
            ToolTip checkboxTooltip = new ToolTip();
            checkboxTooltip.SetToolTip(checkBoxSaveCover, "Check to save new Cover");

            //Context menu
            ContextMenu menu = new ContextMenu();
            menu.MenuItems.Add("Check for Cover", checkForCover_Clicked);
            pictureBoxPic.ContextMenu = menu;

            this.Text = "Update serie";
        }

        private void checkForCover_Clicked(object sender, EventArgs e)
        {
            FindCover();
            checkBoxSaveCover.Visible = true;
            picChange = true;
        }
        

        private void buttonUpdate_Click(object sender, EventArgs e)
        {
            bool update = true;
            if (!CheckError())
            {
                if(!checkBoxSaveCover.Checked && picChange)
                {
                    DialogResult messageResult =
                        MessageBox.Show("Are you sure you don't want to save the new cover?", "Save cover?",
                                        MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                    if( messageResult == DialogResult.Yes)
                    {
                       coverStream = null; 
                    } 
                    else if(messageResult == DialogResult.Cancel)
                    {
                        update = false;
                    }
                }
                if(update)
                {
                    if(nextAirDate.Equals(DateTime.MinValue))
                    {
                        nextAirDate = serie.NextAirDate;
                    }
                    manager.updateSerie(new Serie(textBoxTitel.Text, season, episode, nextAirDate,frequency, serie.CoverPath,curSeason,curEpisode,textBoxDestMovePath.Text), selectedCollection, serie.Titel, coverStream);

                    this.Dispose();
                    reDrawScreen();   
                }
            }
        }

        #endregion

        #region General functions

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        /// <summary>
        /// Check form errors
        /// </summary>
        /// <returns>true: still errors</returns>
        private bool CheckError()
        {
            bool error = false;
            
            //------ check user info ------
            //title
            if(string.IsNullOrEmpty(textBoxTitel.Text))
            {
                errorProvider.SetError(textBoxTitel,"Enter a title please");
                error = true;
            }
            else
            {
                errorProvider.SetError(textBoxTitel, "");
            }
            //season
            if(Information.IsNumeric(textBoxSeason.Text))
            {
                season = int.Parse(textBoxSeason.Text);
                errorProvider.SetError(textBoxSeason, "");
            }
            else
            {
                error = true;
                errorProvider.SetError(textBoxSeason, "Enter a number");
            }
            //episode
            if (Information.IsNumeric(textBoxEpisode.Text))
            {
                episode = int.Parse(textBoxEpisode.Text);
                errorProvider.SetError(textBoxEpisode, "");
            }
            else
            {
                error = true;
                errorProvider.SetError(textBoxEpisode, "Enter a number");
            }


            // ----- Air information ----
            if (checkBoxEnableAirInfo.Checked)
            {
                //cur season
                if (Information.IsNumeric(textBoxCurSeason.Text))
                {
                    curSeason = int.Parse(textBoxCurSeason.Text);
                    errorProvider.SetError(textBoxCurSeason, "");
                }
                else
                {
                    error = true;
                    errorProvider.SetError(textBoxCurSeason, "Enter a number");
                }
                //cur episode
                if (Information.IsNumeric(textBoxCurEpisode.Text))
                {
                    curEpisode = int.Parse(textBoxCurEpisode.Text);
                    errorProvider.SetError(textBoxCurEpisode, "");
                }
                else
                {
                    error = true;
                    errorProvider.SetError(textBoxCurEpisode, "Enter a number");
                }

                //frequention
                if (!textBoxFrequency.Text.Equals("Ex. 7 (every week)"))
                {
                    if (Information.IsNumeric(textBoxFrequency.Text))
                    {
                        frequency = int.Parse(textBoxFrequency.Text);
                        errorProvider.SetError(textBoxFrequency, "");
                    }
                    else
                    {
                        error = true;
                        errorProvider.SetError(textBoxFrequency, "Enter a number");
                    }
                
                }
                else
                {
                    frequency = 0;
                }
            }

            return error;
        }

        
        
        

        /// <summary>
        /// finds a cover based on the title, if found it will be saved in the coverstream (MemoryStream)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="eventArgs"></param>
        [PreEmptive.Attributes.Feature("GetCover",EventType = PreEmptive.Attributes.FeatureEventTypes.Start)]
        private void FindCover(object sender = null, EventArgs eventArgs = null)
        {
            Cursor.Current = Cursors.WaitCursor;
            if (!String.IsNullOrEmpty(textBoxTitel.Text))
            {
                coverStream = manager.getCoverPic(textBoxTitel.Text);

                if (coverStream == null)
                {
                    pictureBoxPic.Image = Image.FromFile(GeneralVars.DEFAULT_COVER_PATH);
                    serie.CoverPath = null;
                }
                else
                {
                    pictureBoxPic.Image = Image.FromStream(coverStream);
                }
            }
            FindCoverCompleted();
        }

        [PreEmptive.Attributes.Feature("GetCover", EventType = PreEmptive.Attributes.FeatureEventTypes.Stop)]
        private void FindCoverCompleted()
        {
            Cursor.Current = Cursors.Default;
        }
        /// <summary>
        /// Shows a dialog to select the next airdate, this is saved in nextAirDate para
        /// </summary>
        private void ShowCalender()
        {
            CalenderForm calenderForm = new CalenderForm();

            if(calenderForm.ShowDialog() == DialogResult.OK)
            {
                nextAirDate = calenderForm.getSelectedDate();
                this.textBoxAirDate.Text = nextAirDate.Date.ToShortDateString();
                calenderForm.Dispose();
            }
        }

        private void buttonCalender_Click(object sender, EventArgs e)
        {
            ShowCalender();
        }

        private void textBoxFrequency_MouseClick(object sender, MouseEventArgs e)
        {
            textBoxFrequency.SelectAll();
        }

        private void buttonBrowseDestMovePath_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog openFolderDialog = new FolderBrowserDialog();

            if (openFolderDialog.ShowDialog() == DialogResult.OK)
            {
                textBoxDestMovePath.Text = openFolderDialog.SelectedPath;
            }
        }

        private void checkBoxEnableAirInfo_CheckedChanged(object sender, EventArgs e)
        {
            groupBoxAirInfo.Enabled = checkBoxEnableAirInfo.Checked;
        }
        
    }

    #endregion

}
